package cn.t.repository.impl;

import cn.t.converter.MailTaskConverter;
import cn.t.core.repoistory.RepositoryImpl;
import cn.t.model.common.MailTaskDO;
import cn.t.persistence.entity.MailTaskPO;
import cn.t.persistence.mapper.MailTaskMapper;
import cn.t.repository.common.MailTaskRepository;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 邮件发送任务表(TMailTask)数据仓库
 *
 * @author t
 * @since 2024-08-27 13:59:11
 */
@Slf4j
@Repository
@AllArgsConstructor
public class MailTaskRepositoryImpl extends RepositoryImpl<MailTaskMapper, MailTaskPO, MailTaskConverter, MailTaskDO> implements MailTaskRepository {


    @Override
    public List<MailTaskDO> findByModel(MailTaskDO MailTaskDO, int start, Integer pageSize, String field, String direction) {

        String lastSql = StringUtils.hasText(field) ?
                " order by " + field + direction + " limit " + start + "," + pageSize
                :
                " limit " + start + "," + pageSize;

        List<MailTaskPO> list = getWrapper(MailTaskDO)
                .last(lastSql)
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }

        return list.stream().map(converter::po2Model).collect(Collectors.toList());
    }

    private LambdaQueryChainWrapper<MailTaskPO> getWrapper(MailTaskDO MailTaskDO) {
        LambdaQueryChainWrapper<MailTaskPO> wrapper = lambdaQuery();
        if (!ObjectUtils.isEmpty(MailTaskDO.getMailTitle())) {
            wrapper.eq(MailTaskPO::getMailTitle, MailTaskDO.getMailTitle());
        }
        if (!ObjectUtils.isEmpty(MailTaskDO.getMailType())) {
            wrapper.eq(MailTaskPO::getMailType, MailTaskDO.getMailType());
        }
        if (!ObjectUtils.isEmpty(MailTaskDO.getEmail())) {
            wrapper.eq(MailTaskPO::getEmail, MailTaskDO.getEmail());
        }
        if (!ObjectUtils.isEmpty(MailTaskDO.getContent())) {
            wrapper.eq(MailTaskPO::getContent, MailTaskDO.getContent());
        }
        if (!ObjectUtils.isEmpty(MailTaskDO.getStatus())) {
            wrapper.eq(MailTaskPO::getStatus, MailTaskDO.getStatus());
        }
        if (!ObjectUtils.isEmpty(MailTaskDO.getPushTime())) {
            wrapper.eq(MailTaskPO::getPushTime, MailTaskDO.getPushTime());
        }

        return wrapper;
    }

    @Override
    public long count(MailTaskDO mailTaskDO) {
        return getWrapper(mailTaskDO).count();
    }
}
